#include <stdio.h>
#include "network.h"
#include "procedure.h"
#include "netdata.h"
#include "../ui/element/Button.h"
#include "UI.h"
int onCreateRoomButtonClick(void *args)
{
    printf("正在创建房间\n");
    if(!StartRoom(">_<")) {
        return 1;
    }
    printf("房间已创建\n");
    printf("正在加入本地房间\n");
    if(!JoinRoom("127.0.0.1")) {
        return 1;
    }
    printf("已进入本地房间\n");
    ShowRoomUI(true);
    return 0;
}
int onFindRoomButtonClick(void *args)
{
    printf("准备开始搜索房间\n");
    if(!StartFindRoom()) { //udpReceiver虽然属于network/base，其实也耦合了procedure
        printf("搜索房间时遇到网络异常\n");
        return 1;
    }
    printf("开始搜索房间\n");
    ShowSearchRoomUI();
    return 0;
}
int onSettingsButtonClick(void *args)
{
    printf("正在进行设置\n");
    return 0;
}
int backHomeFromHost(void *args)
{
    DisconnectServer(true);
    CloseRoom();
    ShowInitUI();
    return 0;
}
int backFindRoomFromRemoteRoom(void  *args)
{
    DisconnectServer(true);//这个是network/base
    onFindRoomButtonClick(nullptr);
    return 0;
}
int backHomeFromFindRoom(void *args)
{
    StopFindRoom();
    ShowInitUI();
    return 0;
}
int backHome(void *args)
{
    ShowInitUI();
    return 0;
}
int onRoomButtonDoubleClick(void *arg)
{
    auto* btn = (Button*) arg;
    char serverAddrStr[16];
    if(ParseIpFromRoomButtonText(btn->getText(), serverAddrStr)) {
        printf("Connecting %s\n",serverAddrStr);
        if(!JoinRoom(serverAddrStr)) {
            return 1;
        }
        ShowRoomUI(false);
    } else {
        printf("ServerAddr parse error\n");
        return 1;
    }
    return 0;
}
int onJoinRoomButtonClick(void *args) {
    char* serverAddrStr = GetInputValue("room-ip");
    printf("Connecting %s\n",serverAddrStr);
    if(serverAddrStr == nullptr || !JoinRoom(serverAddrStr)) {
        return 1;
    }
    //ShowUI在JoinRoom中被调用
    return 0;
}
int onGameStartButtonClick(void *args) {
    ServerStartGame();
    return 0;
}
int onQuitGameButtonDoubleClick(void *args) {
    PlayerGameOver();
    if (IsHost) {
        ServerStopGame();
        backHomeFromHost(nullptr);
    } else {
        backFindRoomFromRemoteRoom(nullptr);
    }
    return 0;
}